/**
 * 网络状态检测和处理工具
 */

import { Alert } from 'react-native';
import React from 'react';

// 网络状态类型
export interface NetworkState {
  isConnected: boolean;
  type: string;
  isInternetReachable: boolean | null;
}

// 网络状态管理器
export class NetworkManager {
  private static instance: NetworkManager;
  private listeners: ((state: NetworkState) => void)[] = [];
  private currentState: NetworkState = {
    isConnected: false,
    type: 'unknown',
    isInternetReachable: null,
  };

  private constructor() {
    this.init();
  }

  static getInstance(): NetworkManager {
    if (!NetworkManager.instance) {
      NetworkManager.instance = new NetworkManager();
    }
    return NetworkManager.instance;
  }

  private init() {
    // 模拟网络状态检测（在实际项目中应该使用 @react-native-community/netinfo）
    this.currentState = {
      isConnected: true,
      type: 'wifi',
      isInternetReachable: true,
    };
  }

  // 获取当前网络状态
  getCurrentState(): NetworkState {
    return this.currentState;
  }

  // 检查网络连接
  async checkConnection(): Promise<NetworkState> {
    const state = await NetInfo.fetch();
    const networkState: NetworkState = {
      isConnected: state.isConnected ?? false,
      type: state.type,
      isInternetReachable: state.isInternetReachable,
    };
    
    this.currentState = networkState;
    return networkState;
  }

  // 添加网络状态监听器
  addListener(listener: (state: NetworkState) => void) {
    this.listeners.push(listener);
    // 立即调用一次，传递当前状态
    listener(this.currentState);
  }

  // 移除网络状态监听器
  removeListener(listener: (state: NetworkState) => void) {
    const index = this.listeners.indexOf(listener);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  }

  // 通知所有监听器
  private notifyListeners(state: NetworkState) {
    this.listeners.forEach(listener => listener(state));
  }

  // 检查是否有网络连接
  isConnected(): boolean {
    return this.currentState.isConnected;
  }

  // 显示网络错误提示
  showNetworkError() {
    Alert.alert(
      '網絡連接失敗',
      '請檢查您的網絡連接並重試',
      [
        { text: '確定' }
      ]
    );
  }
}

// 导出单例实例
export const networkManager = NetworkManager.getInstance();

// 网络状态Hook（用于React组件）
export const useNetworkState = () => {
  const [networkState, setNetworkState] = React.useState<NetworkState>(
    networkManager.getCurrentState()
  );

  React.useEffect(() => {
    const handleNetworkChange = (state: NetworkState) => {
      setNetworkState(state);
    };

    networkManager.addListener(handleNetworkChange);

    return () => {
      networkManager.removeListener(handleNetworkChange);
    };
  }, []);

  return networkState;
};

// 网络请求重试工具
export class RetryManager {
  static async withRetry<T>(
    operation: () => Promise<T>,
    maxRetries: number = 3,
    delay: number = 1000
  ): Promise<T> {
    let lastError: any;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        return await operation();
      } catch (error) {
        lastError = error;
        
        // 如果是网络错误且还有重试次数，则等待后重试
        if (attempt < maxRetries && this.shouldRetry(error)) {
          console.log(`请求失败，第${attempt}次重试，${delay}ms后重试...`);
          await this.sleep(delay);
          delay *= 2; // 指数退避
          continue;
        }
        
        // 如果是最后一次尝试或不应该重试，则抛出错误
        throw error;
      }
    }

    throw lastError;
  }

  private static shouldRetry(error: any): boolean {
    // 网络错误可以重试
    if (error.name === 'TypeError' || error.message?.includes('Network request failed')) {
      return true;
    }
    
    // 5xx服务器错误可以重试
    if (error.status >= 500) {
      return true;
    }
    
    // 超时错误可以重试
    if (error.name === 'AbortError' || error.message?.includes('timeout')) {
      return true;
    }
    
    return false;
  }

  private static sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// 离线数据缓存工具
export class OfflineCache {
  private static cache = new Map<string, { data: any; timestamp: number; ttl: number }>();

  // 设置缓存
  static set(key: string, data: any, ttlMinutes: number = 30) {
    this.cache.set(key, {
      data,
      timestamp: Date.now(),
      ttl: ttlMinutes * 60 * 1000, // 转换为毫秒
    });
  }

  // 获取缓存
  static get(key: string): any | null {
    const item = this.cache.get(key);
    if (!item) {
      return null;
    }

    // 检查是否过期
    if (Date.now() - item.timestamp > item.ttl) {
      this.cache.delete(key);
      return null;
    }

    return item.data;
  }

  // 清除缓存
  static clear(key?: string) {
    if (key) {
      this.cache.delete(key);
    } else {
      this.cache.clear();
    }
  }

  // 清除过期缓存
  static clearExpired() {
    const now = Date.now();
    for (const [key, item] of this.cache.entries()) {
      if (now - item.timestamp > item.ttl) {
        this.cache.delete(key);
      }
    }
  }
}

// 带缓存和重试的API请求工具
export const apiRequest = async <T>(
  operation: () => Promise<T>,
  cacheKey?: string,
  cacheTtlMinutes: number = 5
): Promise<T> => {
  // 如果有缓存键且网络不可用，尝试从缓存获取
  if (cacheKey && !networkManager.isConnected()) {
    const cachedData = OfflineCache.get(cacheKey);
    if (cachedData) {
      console.log('使用离线缓存数据:', cacheKey);
      return cachedData;
    }
  }

  try {
    // 使用重试机制执行请求
    const result = await RetryManager.withRetry(operation);
    
    // 如果有缓存键，保存结果到缓存
    if (cacheKey) {
      OfflineCache.set(cacheKey, result, cacheTtlMinutes);
    }
    
    return result;
  } catch (error) {
    // 如果请求失败且有缓存，使用缓存数据
    if (cacheKey) {
      const cachedData = OfflineCache.get(cacheKey);
      if (cachedData) {
        console.log('请求失败，使用缓存数据:', cacheKey);
        return cachedData;
      }
    }
    
    throw error;
  }
};
